﻿function VotesDownloader(votingSitesPlain, progress) {
	var timeoutID;
	var fixedLinesAmount = 20;

	function processSite(node, completnessHandler) {
		$.ajax({
			url: node.href,
			cache: false,
			dataType: 'html',
			success: function (page) {
				var $votesByDistrictTable = $($("td:nth-child(2)>div>table", page)[0]);
				var options = $("tr", $votesByDistrictTable).length - fixedLinesAmount;
				var $districts = $("tr:nth-child(1)>td", $votesByDistrictTable);
				var $votersListed$01 = $("tr:nth-child(2)>td", $votesByDistrictTable);
				var $invalidBulletins$09 = $("tr:nth-child(10)>td", $votesByDistrictTable)
				var $validBulletins$10 = $("tr:nth-child(11)>td", $votesByDistrictTable);
				var $voteCells = [];

				for (var i = 0; i < options; ++i)
					$voteCells.push($("tr:nth-child(" + (21 + i) + ")>td", $votesByDistrictTable));

				node.districts = [];

				$.each($districts, function (i, col) {
					var districtData = {
						name: $(col).text(),
						votersListed: 1 * $($votersListed$01[i]).text(),
						invalidBulletins: 1 * $($invalidBulletins$09[i]).text(),
						validBulletins: 1 * $($validBulletins$10[i]).text(),
						votes: []
					};

					$.each($voteCells, function (j, $cell) {
						districtData.votes.push(1 * $("b", $cell[i]).text());
					});

					node.districts.push(districtData);
				});
			},
			complete: function () {
				completnessHandler();
			}
		});
	}

	function runDownloads(startIndex, lengthLimit) {
		var batchSize = 15;
		var final = false;

		if (startIndex + batchSize >= lengthLimit) {
			final = true;
			batchSize = lengthLimit - startIndex;
		}

		var remainder = batchSize;

		clearTimeout(timeoutID);
		for (var i = 0; i < batchSize; ++i)
			processSite(votingSitesPlain[startIndex + i], function () {
				if (0 == --remainder) {
					var nextStartIndex = startIndex + batchSize;

					if (!final)
						timeoutID = setTimeout(function () { runDownloads(nextStartIndex, lengthLimit); }, 20);
					progress(nextStartIndex, final);
				}
			});
	}

	this.run = function () {
		progress(0);
		timeoutID = setTimeout(function () { runDownloads(0, votingSitesPlain.length); }, 20);
	};
}
